package com.cfushn.ddd.tools.maths;

import java.math.BigDecimal;

/**
 * DivisionUtil
 *
 * @author CFuShn 2021/10/18 11:33
 */
@SuppressWarnings("unused")
public class DivisionUtil {

    private static final double ZERO = 0.000001;

    private DivisionUtil() {
    }

    /**
     * 同比计算(返回一个0~1间的小数,保留3位小数)
     */
    public static double csy(Object now, Object last) {
        try {
            return digitsDouble((division(getDouble(now) - getDouble(last), last)), 3);
        } catch (Exception e) {
            return 0.0;
        }
    }

    /**
     * 两数相除,返回double,保留两位
     *
     * @param dividend 除数
     * @param divisor  被除数
     * @return double
     */
    public static double division(Object dividend, Object divisor) {
        return division(dividend, divisor, 2);
    }

    /**
     * 两数相除,返回double
     *
     * @param dividend 除数
     * @param divisor  被除数
     * @param digits   保留小数位
     * @return double
     */
    public static double division(Object dividend, Object divisor, int digits) {

        double dividendDouble = getDouble(dividend);
        double divisorDouble = getDouble(divisor);

        if (abs(divisorDouble - 0) < ZERO || digits < 0) {
            return 0;
        }
        return digitsDouble(dividendDouble / divisorDouble, digits);
    }

    public static double getDouble(Object num) {
        if (num instanceof BigDecimal) {
            return ((BigDecimal) num).doubleValue();
        }
        if (num instanceof String) {
            return Double.parseDouble((String) num);
        }
        if (num instanceof Integer) {
            return ((Integer) num).doubleValue();
        }
        if (num instanceof Double) {
            return (Double) num;
        }
        return 0.0;
    }

    public static double digitsDouble(Object d, int digits) {
        String temp = "%." + digits + "f";
        return Double.parseDouble(String.format(temp, getDouble(d)));
    }

    public static String digitsToStr(Object d, int digits) {
        String temp = "%." + digits + "f";
        return String.format(temp, getDouble(d));
    }

    public static double abs(double d) {
        return d > 0 ? d : d * -1;
    }
}
